﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemyManager : MonoBehaviour 
{
  #region Instance
  private static EnemyManager instance_;
  private static readonly object lock_obj_ = new object();
  public static EnemyManager Instance
  {
    get
    {
      if (instance_ == null)
      {
        lock (lock_obj_)
        {
          if (instance_ == null)
          {
            GameObject obj = GameObject.Find("EnemyManager");
            EnemyManager mgr = obj.GetComponent<EnemyManager>();
            if (mgr == null)
              instance_ = obj.AddComponent<EnemyManager>() as EnemyManager;
            else
              instance_ = mgr;
          }
        }
      }

      return instance_;
    }
  }
  #endregion

  public GameObject prefab;
  public Vector3[] Style;

  private Transform spawnPoint;
  private List<GameObject> playList = new List<GameObject>();
  private List<GameObject> getoutList = new List<GameObject>();

  void Start()
  {

    spawnPoint = GameObject.Find("SpawnPoint").transform;

    Invoke("createEnemy", GlobalSetting.EnemySpawnTime);
  }
  void createEnemy()
  {
    if (Style.Length == 0)
      return;

    int idx = Random.Range(0, Style.Length);

    Vector3 pos = new Vector3(Random.Range(-1.5f, 1.5f)
      , spawnPoint.position.y
      , spawnPoint.position.z);

    GameObject obj;
    if(getoutList.Count > 0)
    {
      obj = getoutList[getoutList.Count - 1];
      getoutList.RemoveAt(getoutList.Count - 1);
      obj.transform.position = pos;
    }
    else 
    {
      obj = Instantiate(prefab, pos, Quaternion.identity) as GameObject;
    }

    obj.SetActive(true);
    playList.Add(obj);
    Transform spriteTrans = GameObjectHelper.Find<Transform>(obj.transform, "Sprite", false);
    spriteTrans.localScale = Style[idx];
    spriteTrans.gameObject.AddComponent<BoxCollider2D>();

    Invoke("createEnemy", GlobalSetting.EnemySpawnTime);
  }



  public void leave(GameObject obj)
  {
    if(obj == null)
      return;
    obj.SetActive(false);
    playList.Remove(obj);
    getoutList.Add(obj);
  }
}
